﻿using ECMS.AppService.Model.Models;
using ECMS.AppService.Model.Requests;
using ECMS.AppService.Model.Responses;
using ECMS.Domain.Models;
using ECMS.Infrastructure.ClientData;
using ECMS.Infrastructure.Domain;
using ECMS.Infrastructure.Extensions;
using ECMS.Infrastructure.Helper;
using Microsoft.EntityFrameworkCore;
using QuestionBank.Infrastructure.Helper;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace ECMS.AppService.Implements
{
    /// <summary>
    /// 管理员服务
    /// </summary>
    public partial class SysUserService
    {
        public async Task<ApiResult<SaveResponse>> SaveAsync(SysUserModel model)
        {
            var response = new ApiResult<SaveResponse>
            {
                StatusCode = 200
            };
            try
            {
                if (model == null)
                    throw new ArgumentNullException(nameof(model));
                SysUser entity;
                if (model.Guid == null)
                {
                    // 用户名唯一检查
                    if (Query().Any(p => p.LoginName == model.LoginName))
                    {
                        response.Message = "登录已存在,请更改.";
                        return response;
                    }
                    // 手机号唯一检查
                    if (Query().Any(p => p.Mobile == model.Mobile))
                    {
                        response.Message = "手机号已存在,请更改.";
                        return response;
                    }

                    entity = new SysUser
                    {
                        LoginName = model.LoginName,
                        Password = CryptoHelper.DESEncrypt(model.Password),
                        Mobile = model.Mobile,
                        RealName = model.RealName,
                        IsLock = model.IsLock,
                        LockTime = model.LockTime,
                        UnLockTime = model.UnLockTime,
                        LastLoginTime = model.LastLoginTime
                    };

                    await _unitofwork.RegisterNewAsync(entity);
                }
                else
                {
                    // 用户名唯一检查
                    if (Query().Any(p => p.LoginName == model.LoginName && p.Guid != model.Guid))
                    {
                        response.Message = "登录已存在,请更改.";
                        return response;
                    }
                    // 手机号唯一检查
                    if (Query().Any(p => p.Mobile == model.Mobile && p.Guid != model.Guid))
                    {
                        response.Message = "手机号已存在,请更改.";
                        return response;
                    }

                    entity = await Query().Where(p => p.Guid == model.Guid).FirstOrDefaultAsync();
                    if (entity == null)
                    {
                        response.Message = "找不到该用户信息，更新失败.";
                        return response;
                    }
                    entity.LoginName = model.LoginName;
                    if (entity.Password != model.Password)
                        entity.Password = CryptoHelper.DESEncrypt(model.Password);
                    entity.Mobile = model.Mobile;
                    entity.RealName = model.RealName;
                    entity.IsLock = model.IsLock;
                    entity.LockTime = model.LockTime;
                    entity.UnLockTime = model.UnLockTime;
                    entity.LastLoginTime = model.LastLoginTime;
                    _unitofwork.RegisterDirty(entity);
                }
                var flag = await _unitofwork.CommitAsync();
                response.Success = flag;
                response.Message = flag ? "保存成功." : "保存失败.";

            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }

            return response;
        }

        public async Task<ApiResult<Page<SysUserResponse>>> GetPagesAsync(GetSysUserPagesRequest request)
        {
            var response = new ApiResult<Page<SysUserResponse>>
            {
                StatusCode = 200
            };
            try
            {
                if (request == null)
                    throw new ArgumentNullException(nameof(request));
                var result = await Query()
                    .HasWhere(request.LoginName, p => p.LoginName.Contains(request.LoginName))
                    .HasWhere(request.RealName, p => p.RealName.Contains(request.RealName))
                    .HasWhere(request.Mobile, p => p.Mobile.Contains(request.Mobile))
                    .OrderByDescending(p => p.Id)
                    .ToPageAsync(request.PageIndex, request.PageSize);

                var flag = result.Items != null && result.Items.Count > 0;
                response.Success = flag;
                response.Message = flag ? "获取成功." : "暂无数据.";

                if (flag)
                {
                    response.Data = result.ToViewPage(u => new SysUserResponse
                    {
                        LoginName = u.LoginName,
                        Mobile = u.Mobile,
                        Guid = u.Guid,
                        Id = u.Id,
                        Password = u.Password,
                        RealName = u.RealName,
                        CreateTime = u.CreateTime,
                        IsLock = u.IsLock,
                        LockTime = u.LockTime,
                        UnLockTime = u.UnLockTime,
                        LastLoginTime = u.LastLoginTime
                    });
                }

            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }

            return response;
        }

        public async Task<SysUserResponse> GetDetailAsync(Guid guid)
        {
            var u = await Query().FirstOrDefaultAsync(p => p.Guid == guid);
            if (u == null)
                return new SysUserResponse();
            return new SysUserResponse
            {
                Guid = u.Guid,
                Id = u.Id,
                LoginName = u.LoginName,
                Mobile = u.Mobile,
                Password = u.Password,
                RealName = u.RealName,
                IsLock = u.IsLock,
                LockTime = u.LockTime,
                UnLockTime = u.UnLockTime,
                LastLoginTime = u.LastLoginTime
            };
        }

        public async Task<ApiResult<string>> DeleteAsync(Guid? guid)
        {
            var response = new ApiResult<string>
            {
                StatusCode = 200
            };
            try
            {
                if (guid == null)
                    throw new ArgumentNullException(nameof(guid));
                // 物理删除
                Delete(p => p.Guid == guid);

                var flag = await _unitofwork.CommitAsync();
                response.Success = flag;
                response.Message = flag ? "移除成功." : "移除失败.";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }

            return response;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ApiResult<SysUserResponse>> LoginAsync(LoginRequest request)
        {
            var response = new ApiResult<SysUserResponse>();
            try
            {
                // 读取用户信息
                var entity = await Query().FirstOrDefaultAsync(p => p.LoginName == request.LoginName || p.Mobile == request.LoginName);
                if (entity == null)
                {
                    response.Message = "用户不存在.";
                    return response;
                }
                if (entity.Password != CryptoHelper.DESEncrypt(request.Password))
                {
                    response.Message = "用户名或密码错误.";
                    return response;
                }
                if (entity.IsLock && entity.LockTime > DateTime.Now)
                {
                    response.Message = $"帐号已锁定,于{entity.UnLockTime.ToString("yyyy-MM-dd HH:mm:ss")}自动解锁.";
                    return response;
                }

                if (entity.IsLock)
                {
                    entity.IsLock = false;// 帐号解除锁定
                    _unitofwork.RegisterDirty(entity);
                    await _unitofwork.CommitAsync();
                }
                response.Success = true;
                response.Message = "验证成功.";
                response.Data = new SysUserResponse
                {
                    Guid = entity.Guid,
                    Id = entity.Id,
                    LoginName = entity.LoginName,
                    Mobile = entity.Mobile,
                    RealName = entity.RealName,
                };
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ApiResult<SysUserResponse>> RegisterAsync(RegisterRequest request)
        {
            var response = new ApiResult<SysUserResponse>();
            
            try
            {
                // 读取用户信息
                var entity = await Query().FirstOrDefaultAsync(p => p.LoginName == request.LoginName)??new SysUser();
               
                entity.CreateTime = DateTime.Now;
                entity.LoginName = request.LoginName;
                entity.RealName = "管理员";
                entity.LastChangeTime = DateTime.Now;
                entity.LastLoginTime = DateTime.Now;
                entity.Password = CryptoHelper.DESEncrypt(request.Password);
               
                _unitofwork.RegisterNew(entity);

                var flag = await _unitofwork.CommitAsync();
                response.Success = flag;
                response.Message = flag ? "注册成功." : "注册失败.";
                response.Data = new SysUserResponse
                {
                    Guid = entity.Guid,
                    Id = entity.Id,
                    RealName = entity.RealName,
                    LoginName = entity.LoginName,
                    Password = entity.Password
                };
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }
    }
}
